import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../models/forum_message.dart';
import '../../services/auth_service.dart';
import '../../services/forum_service.dart';
import '../../services/user_service.dart';

class ForumLogic extends GetxController {
  final AuthService _authService = AuthService();
  final ForumService _forumService = ForumService();
  final UserService _userService = UserService();
  
  final messageController = TextEditingController();
  final isLoading = true.obs;
  final isAdmin = false.obs;
  final currentUserId = RxnInt();
  final RxList<ForumMessage> messageList = <ForumMessage>[].obs;
  
  @override
  void onInit() {
    super.onInit();
    _checkIfAdmin();
    _getCurrentUserId();
    loadMessages();
  }
  
  @override
  void onClose() {
    messageController.dispose();
    super.onClose();
  }
  
  Future<void> _checkIfAdmin() async {
    isAdmin.value = await _authService.isCurrentUserAdmin();
  }
  
  Future<void> _getCurrentUserId() async {
    currentUserId.value = await _authService.getCurrentUserId();
  }
  
  Future<void> loadMessages() async {
    isLoading.value = true;
    try {
      final messages = await _forumService.getAllMessages();
      messageList.value = messages;
    } catch (e) {
      SmartDialog.showToast('加载论坛消息失败: $e');
    } finally {
      isLoading.value = false;
    }
  }
  
  Future<void> addMessage() async {
    if (messageController.text.trim().isEmpty) {
      SmartDialog.showToast('消息内容不能为空');
      return;
    }
    
    try {
      final userId = await _authService.getCurrentUserId();
      if (userId == null) {
        SmartDialog.showToast('用户未登录');
        return;
      }
      
      final username = await _authService.getCurrentUsername() ?? '未知用户';
      
      final now = DateTime.now();
      final message = ForumMessage(
        content: messageController.text.trim(),
        publishDate: now.toString(),
        userId: userId,
        username: username,
      );
      
      await _forumService.insertMessage(message);
      messageController.clear();
      SmartDialog.showToast('发布成功');
      await loadMessages();
    } catch (e) {
      SmartDialog.showToast('发布失败: $e');
    }
  }
  
  Future<void> deleteMessage(int messageId) async {
    try {
      await _forumService.deleteMessage(messageId);
      SmartDialog.showToast('删除成功');
      await loadMessages();
    } catch (e) {
      SmartDialog.showToast('删除失败: $e');
    }
  }
  
  bool canDeleteMessage(ForumMessage message) {
    // Admin can delete any message
    if (isAdmin.value) return true;
    
    // User can only delete their own messages
    return message.userId == currentUserId.value;
  }
}
